package com.itany.corejava.code13_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author 石小俊
 * @date 2023年05月26日 15:57
 */
public class Test05_分页查询 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入查询第几页数据:");
        int pageNo = sc.nextInt();
        System.out.print("请输入每页显示多少条数据:");
        int pageSize = sc.nextInt();
        try {
            List<User> users = selectPage(pageNo,pageSize);
            for(User user : users){
                System.out.println(user);
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
    }

    public static List<User> selectPage(Integer pageNo, Integer pageSize) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" limit ?,? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            // 查询第pageNo页的数据,每页显示pageSize条
            // limit (pageNo - 1) * pageSize,pageSize
            ps.setInt(1, (pageNo - 1) * pageSize);
            ps.setInt(2, pageSize);
            rs = ps.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                users.add(user);
            }
            return users;
        } catch (DataAccessException e) {
            throw e;
        } catch (SQLException e) {
            throw new DataAccessException("数据访问异常");
        } finally {
            JDBCUtil.close(conn, ps, rs);
        }
    }

}
